﻿using System;
using System.Windows.Controls;
using WickedFlame.Core.Shapes;
using WickedFlame.Core.Layers;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace WickedFlame.Util.Controls
{
    /// <summary>
    /// Class for drawing mini canvases.
    /// Is used as canvas in the LayerDisplay in the LayerDialog.
    /// Can be used in any place where a layer or a canvas has to be drawn.
    /// </summary>
    public class LayerImage : System.Windows.Controls.Control // Canvas
    {
        public LayerImage()
        {
            this.Loaded += new System.Windows.RoutedEventHandler(OnLoaded);
        }

        void OnLoaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Layer != null)
            {
                Layer.SizeChanged += new System.Windows.SizeChangedEventHandler(OnSizeChanged);
                this.Width = Layer.Width;
                this.Height = Layer.Height;
            }

            //this.Clip = new System.Windows.Media.RectangleGeometry(new System.Windows.Rect(0, 0, this.ActualWidth, this.ActualHeight));
            this.Clip = new System.Windows.Media.RectangleGeometry(new System.Windows.Rect(0, 0, this.Width, this.Height));
        }

        public CanvasLayer Layer
        {
            get
            {
                return (CanvasLayer)GetValue(LayerProperty);
            }
            set
            {
                SetValue(LayerProperty, value);
            }
        }

        public static readonly DependencyProperty LayerProperty =
            DependencyProperty.Register("Layer", typeof(CanvasLayer), typeof(LayerImage), new PropertyMetadata(new PropertyChangedCallback(OnLayerPropertyChanged)));//, new CoerceValueCallback(CoerceText), true, UpdateSourceTrigger.PropertyChanged));

        private static void OnLayerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            
        }

        protected override void OnRender(System.Windows.Media.DrawingContext dc)
        {
            base.OnRender(dc);
            dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, Width, Height));
            if (Layer != null)
            {
                foreach (VectorShape shape in Layer.ShapeList)
                {
                    shape.Draw(dc);
                }
            }
        }

        private void OnSizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
        {
            this.Width = e.NewSize.Width;
            this.Height = e.NewSize.Height;

            this.Clip = new System.Windows.Media.RectangleGeometry(new System.Windows.Rect(0, 0, this.Width, this.Height));
        }
    }
}
